<!--
 * @Author: mayijun
 * @Date: 2022-07-12 09:49:41
 * @LastEditors: mayijun
 * @LastEditTime: 2022-08-10 10:22:29
-->
<script lang="ts" setup>
import API from '@/services';
import { PropType, reactive, ref, watch } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import ModelDataResult from '../modelDataResult/index.vue';
import ContentEdit from '../contentEdit/index.vue';
import { Message } from '@arco-design/web-vue';
import Bus from '@/utils/emmit';
import { store } from '@/store';
import _ from 'lodash';

const route = useRoute();
const router = useRouter();

const props = defineProps({
  deriveDetailData: {
    type: Object as PropType<defs.DerivedDevelopDto>,
    default: () => {}
  }
});
//上线状态
let status = ref<any>(route.query.status);

const state = reactive({
  developType: '1', //开发方式
  resizeHeight: 0 as any, //数据结果拖拽高度
  dimensionList: [] as any[], //可用维度列表
  dimensionIdList: [] as any[], //可用维度已选
  metricsId: route.query.metricsId as any,
  timeframe: '',
  inNotTimeframe: false //验证时间频度是否通过
});

//表格参数
let formParams = reactive({
  pageNum: 1,
  pageSize: 10,
  status: 0,
  type: 0 // 0 表视角；1指标视角
});

// 是否展示预览结果
const isShowPreview = ref<Boolean>(false);

// 预览的表视角数据
const previewData: any = ref(null);

// 预览指标视角数据
const indexViewData: any = ref(null);

//数据预览提交结构
const deriveModel = ref<defs.DerivedDevelopDto>({
  factorList: []
});

//计算规则
const contentEditRef = ref();

//统计周期集合
const timeframeArray = ref<any[]>([]);

/**
 * @description 预览
 * @tabType  0：表视角；1：指标视角
 * @status 0:草稿；1：上线；2：下线
 */
const handlePreviewData = async (tabType: any) => {
  let isTrue = commonParams(tabType);
  if (!isTrue) {
    return false;
  }
  let model = _.cloneDeep(deriveModel.value);
  model.factorList = model.factorList.filter((item: any) => item != undefined);
  //数据预览
  const { code, data } =
    await API.metricsModelRelation.postGetDerivedDevelopData(model);
  if (code === 200) {
    if (tabType === 0) {
      previewData.value = data;
    } else if (tabType === 1) {
      indexViewData.value = data;
    }
    //没有打开，直接打开
    if (!isShowPreview.value) {
      isShowPreview.value = true;
      state.resizeHeight = null;
    }
  }
};

/**
 * @description 保存、保存并上线
 * @type  类型；保存还是保存并上线
 * @status 0:草稿；1：上线；2：下线
 * @remark 描述
 * @successTip 成功提示
 */
const handleSaveMetrics = async (
  type: string,
  status: any,
  remark: string,
  successTip: string
) => {
  formParams.status = status;
  let isTrue = commonParams(0);
  if (!isTrue) {
    return false;
  }
  let model = _.cloneDeep(deriveModel.value);
  model.factorList = model.factorList.filter((item: any) => item != undefined);
  model.remark = remark;

  if (type == 'editSave') {
    try {
      const { code } = await API.metricsModelRelation.postUpdateDerivedDevelop(
        model
      );
      if (code === 200) {
        router.go(-1);
        Message.success(successTip);
      }
    } catch (error) {}
  } else {
    try {
      const { code } = await API.metricsModelRelation.postSaveDerivedDevelop(
        deriveModel.value
      );
      if (code === 200) {
        router.go(-1);
        Message.success(successTip);
      }
    } catch (error) {}
  }
};

// 保存并上线---保存
Bus.on('saveFromDerive', (n: number, remark: string) => {
  let successTip = n ? '保存并上线成功' : '保存成功';
  //let failTip = n ? '保存并上线失败' : '保存失败';
  if (route.query.id) {
    // 编辑态
    handleSaveMetrics('editSave', n, remark, successTip);
  } else {
    // 新建
    handleSaveMetrics('buildSave', n, remark, successTip);
  }
});

//参数整理
const commonParams = (tabType: any) => {
  let text = contentEditRef.value.ruleRef.innerText;
  if (text == '') {
    Message.warning('请输入计算规则');
    return false;
  }
  //时间频度
  if (state.inNotTimeframe) {
    Message.warning('因子配置的统计周期需要保持一致');
    return false;
  }

  //派生指标id
  let derivedMetricsId: any = route.query.metricsId;
  deriveModel.value.derivedMetricsId = derivedMetricsId;
  deriveModel.value.countRules = text.replace(/[\u200b]/g, '');
  //时间频度
  deriveModel.value.timeframe = state.timeframe;
  //维度
  deriveModel.value.dimList = state.dimensionIdList;

  deriveModel.value.type = tabType;
  deriveModel.value.status = formParams.status;
  deriveModel.value.pageNum = formParams.pageNum;
  deriveModel.value.pageSize = formParams.pageSize;

  return true;
};

// 数据结果切换分页
const changePageNum = (v: any, type: any) => {
  let { pageNum, pageSize } = v;
  formParams.pageNum = pageNum;
  formParams.pageSize = pageSize;
  handlePreviewData(type);
};

// 数据结果切换分页
const changePageSize = (v: any, type: any) => {
  let { pageNum, pageSize } = v;
  formParams.pageNum = pageNum;
  formParams.pageSize = pageSize;
  handlePreviewData(type);
};

// 数据结果切换tab
const changeTableTab = (v: any) => {
  handlePreviewData(Number(v));
};

//可用维度列表
const getDerivedDimList = async (findList: any[]) => {
  let list = findList.filter((item) => item != undefined);
  const { code, data } = await API.metricsModelRelation.postGetDerivedDimList({
    list
  });
  if (code === 200 && Array.isArray(data)) {
    state.dimensionList = data;
    if (!route.query.id) {
      //可用维度列表默认全部选中
      state.dimensionIdList = state.dimensionList.map(
        (item: any) => item.dimensionId
      );
    }
    if (state.dimensionList.length == 0) {
      state.dimensionIdList = [];
    }
  }
};

//详情展示
const getDetailData = (obj: defs.DerivedDevelopDto) => {
  deriveModel.value = obj;
  if (obj.status) {
    formParams.status = obj.status;
  }
  if (obj.pageNum) {
    formParams.pageNum = obj.pageNum;
  }
  if (obj.pageSize) {
    formParams.pageSize = obj.pageSize;
  }
  //可用维度处理
  if (obj.dimList && obj.factorList) {
    let findList = obj.factorList.map((item) => {
      return { metricsId: item.metricsId, modelId: item.modelId };
    });
    getDerivedDimList(findList);
    state.dimensionIdList = obj.dimList;
  }
  //时间频度处理
  if (obj.timeframe) {
    state.timeframe = obj.timeframe;
  }
};

//监控统计周期变化
watch(
  () => timeframeArray.value,
  (val) => {
    if (val) {
      console.log(123);
      
      //是否有选择统计周期
      let isSelect = false;
      deriveModel.value.factorList?.map((item) => {
        if (item && item.countCycleDto) {
          isSelect = true;
        }
      });
      //有选择，所有指标的统计周期需要保持一致
      if (isSelect) {
        let unitArray: any[] = [];
        deriveModel.value.factorList?.map((item) => {
          //有的选了，有的没有选择
          if (item && item.countCycleDto) {
            unitArray.push(item.countCycleDto.unit);
          } else {
            let time = timeframeArray.value.find(
              (obj) => item && obj.id == item.metricsId
            );
            if (time) {
              unitArray.push(time.timeframe);
            }
          }
        });
        //取数组第一个值，判断数组中的值是否一致
        let timeframe = unitArray[0];
        let someTime = unitArray.every((item) => item === timeframe);
        console.log(unitArray);
        //不一致提示
        if (!someTime) {
          state.timeframe = '';
          state.inNotTimeframe = true;
        } else {
          state.timeframe = timeframe;
          state.inNotTimeframe = false;
        }
      } else {
        //没有选择，说明都是聚合的，取最大粒度
        let unitArray = timeframeArray.value.map(
          (item) => item && item.timeframe
        );
        let year = unitArray.find((item) => item == 'year');
        let quarter = unitArray.find((item) => item == 'quarter');
        let month = unitArray.find((item) => item == 'month');
        let week = unitArray.find((item) => item == 'week');
        let day = unitArray.find((item) => item == 'day');
        let hour = unitArray.find((item) => item == 'hour');
        if (year) {
          state.timeframe = year;
        } else if (quarter) {
          state.timeframe = quarter;
        } else if (month) {
          state.timeframe = month;
        } else if (week) {
          state.timeframe = week;
        } else if (day) {
          state.timeframe = day;
        } else if (hour) {
          state.timeframe = hour;
        } else {
          state.timeframe = '';
        }
      }
    }
  },
  {
    deep: true
  }
);
//详情处理
watch(
  () => props.deriveDetailData,
  (val) => {
    if (val) {
      getDetailData(val);
    }
  }
);
</script>
<template>
  <div class="from-deriver-content">
    <div class="develop-type">
      <span class="label">开发方式：</span>
      <a-tabs v-model="state.developType" :disabled="status == 1">
        <a-tab-pane key="1" title="配置"></a-tab-pane>
        <a-tab-pane key="2" title="SQL"></a-tab-pane>
      </a-tabs>
    </div>
    <div
      class="condision"
      :style="{
        height:
          state.resizeHeight > 0
            ? `calc(100vh - 142px - ${state.resizeHeight}px)`
            : state.resizeHeight == null
            ? `calc(100vh - 142px - 50%)`
            : ''
      }"
    >
      <div class="item-li rule-li">
        <span class="title">计算规则：</span>
        <ContentEdit
          :deriveModel="deriveModel"
          :metricsId="state.metricsId"
          :dimensionList="state.dimensionList"
          :timeframeArray="timeframeArray"
          ref="contentEditRef"
          @getDerivedDimList="getDerivedDimList"
        ></ContentEdit>
      </div>
      <div class="item-li">
        <span class="title">时间频度：</span>
        <div class="index-time" v-if="state.timeframe == 'hour'">时</div>
        <div class="index-time" v-else-if="state.timeframe == 'day'">日</div>
        <div class="index-time" v-else-if="state.timeframe == 'week'">周</div>
        <div class="index-time" v-else-if="state.timeframe == 'month'">月</div>
        <div class="index-time" v-else-if="state.timeframe == 'quarter'">
          季
        </div>
        <div class="index-time" v-else-if="state.timeframe == 'year'">年</div>
        <div class="index-time" v-else>-</div>
      </div>
      <div class="item-li dimension">
        <div class="title">可用维度：</div>
        <a-select
          :disabled="status == 1"
          placeholder="请选择"
          v-model="state.dimensionIdList"
          :options="state.dimensionList"
          :field-names="{ value: 'dimensionId', label: 'columnDimName' }"
          size="large"
          multiple
        >
          <template #arrow-icon>
            <icon-caret-down />
          </template>
        </a-select>
      </div>
      <div class="item-li">
        <div class="title"></div>
        <a-button type="outline" @click="handlePreviewData(0)"
          >数据预览</a-button
        >
      </div>
    </div>
    <a-resize-box
      :directions="['top']"
      class="initTable"
      v-model:height="state.resizeHeight"
      :style="{ height: !isShowPreview ? 0 : '50%' }"
    >
      <template #resize-trigger>
        <div class="resizebox-demo resizebox-demo-horizontal">
          <div class="resizebox-demo-line"></div>
        </div>
      </template>
      <div class="table-result">
        <div class="table-result-title">
          <div class="tabs-name"><span>数据结果</span></div>
          <div :style="{ cursor: 'pointer' }">
            <icon-caret-down
              v-if="isShowPreview"
              @click="
                () => {
                  isShowPreview = !isShowPreview;
                  state.resizeHeight = 0;
                }
              "
            />
            <icon-caret-up
              v-if="!isShowPreview"
              @click="
                () => {
                  isShowPreview = !isShowPreview;
                  state.resizeHeight = null;
                }
              "
            />
          </div>
        </div>
        <div class="table-result-data" v-show="isShowPreview">
          <model-data-result
            ref="defaultTabsRef"
            :preview-data="previewData"
            :index-view-data="indexViewData"
            @changePageNum="changePageNum"
            @changePageSize="changePageSize"
            @changeTableTab="changeTableTab"
          >
          </model-data-result>
        </div>
      </div>
    </a-resize-box>
  </div>
</template>
<style lang="scss" scoped>
@import './index.scss';
</style>